import cn from 'classnames';
import PropTypes from 'prop-types';
import React, { useEffect, useState } from 'react';
import {
	Search24 as SearchIcon,
	ChevronDown16 as ChevronDown,
} from '@carbon/icons-react';
import fetchFer from 'API/fetch';
import { withRouter } from 'react-router';
import Button from '@kuiper-components/button';
import Input from '@kuiper-components/input';
import Cascader from 'antd/lib/cascader';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import s from './style.module.css';
import CreateJob from './CreateJob';
import CreateHostJob from './CreateHostJob';
import Select, { Option } from '@kuiper-components/select';
import KSelect from '@knownsec/react-component/dist/Select';
import notification from '@kuiper-components/notification';
import confirm from '../../../components/confirm';
import { Link } from 'react-router-dom';
import Tooltip from '@kuiper-components/tooltip';
import KTooltip from '@knownsec/react-component/dist/Tooltip';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
import Message from '@knownsec/react-component/dist/Message';
import KDialog from '@knownsec/react-component/dist/Dialog';
import Form from '@knownsec/react-component/dist/Form';
import KInput from '@knownsec/react-component/dist/Input';
import Textarea from '@knownsec/react-component/dist/Textarea';
import Icon from '@knownsec/react-component/dist/Icon';
import EmptyData from '../../../components/empty/EmptyData';
import { filterNull } from '../../../../common/validation/common';
import { HostColumns, WebColumns } from './columns';
import { cloneDeep } from 'lodash';
import pathOr from 'ramda/es/pathOr';
import { Progress, Menu, Dropdown, Checkbox } from 'antd';
import { getResD } from '../../../index';
import moment from 'moment';
import { WARNING_CATEGORY_KEY_LABEL_MAP } from '../../../../common/constants';
const { SHOW_CHILD } = Cascader;

const turnToUrlparam = obj => {
	let urls = '';
	const hasValKey = Object.keys(obj)
		.filter(item => obj[item] || obj[item] === false || obj[item] === 0)
		.map(i => {
			return i + '=' + obj[i];
		});
	urls = hasValKey.join('&');
	return urls;
};
const TaskMap = {
	vul: 'Web漏洞',
	ssl: 'SSL安全',
	security_event: '安全事件',
	content: '内容违规',
	change_check: '篡改',
};
const TaskMap2 = Object.keys(TaskMap).reduce((t, k) => {
	if (k === 'security_event') {
		t[TaskMap[k]] = 'securityEvent';
	} else if (k === 'change_check') {
		t[TaskMap[k]] = 'changeCheck';
	} else {
		t[TaskMap[k]] = k;
	}
	return t;
}, {});
const TaskSubMap = {
	vul: {
		critical: '严重',
		high: '高危',
		medium: '中危',
		low: '低危',
	},
	ssl: {
		high: '高危',
		medium: '中危',
		low: '低危',
	},
	security_event: WARNING_CATEGORY_KEY_LABEL_MAP.securityEvent,
	content: WARNING_CATEGORY_KEY_LABEL_MAP.content,
	change_check: WARNING_CATEGORY_KEY_LABEL_MAP.changeCheck,
};
const levelMap = {
	严重: 5,
	高危: 4,
	中危: 3,
	低危: 2,
	安全: 1,
	未知: 0,
};
const casList = ['Web漏洞', 'SSL安全', '安全事件', '内容违规', '篡改'].map(
	i => {
		return {
			name: i,
			label: i,
			parent: '',
			value: TaskMap2[i],
			children: ['Web漏洞', 'SSL安全'].includes(i)
				? Object.keys(levelMap).map(k => {
						return {
							label: k,
							name: k,
							parent: i,
							value: levelMap[k],
						};
				  })
				: i === '安全事件'
				? Object.entries(WARNING_CATEGORY_KEY_LABEL_MAP.securityEvent).map(
						([key, label]) => {
							return {
								label,
								name: label,
								parent: i,
								value: key,
							};
						}
				  )
				: i === '内容违规'
				? Object.entries(WARNING_CATEGORY_KEY_LABEL_MAP.content).map(
						([key, label]) => {
							return {
								label,
								name: label,
								parent: i,
								value: key,
							};
						}
				  )
				: i === '篡改'
				? Object.entries(WARNING_CATEGORY_KEY_LABEL_MAP.changeCheck).map(
						([key, label]) => {
							return {
								label,
								name: label,
								parent: i,
								value: key,
							};
						}
				  )
				: [],
		};
	}
);
const resultCol = item => {
	return Object.keys(TaskMap).map(taskType => {
		return {
			title: (
				<div className={cn(s.tac)}>
					{TaskMap[taskType]}
					<br />
					<span style={{ color: item[taskType]?.color || '#686C78' }}>
						{item[taskType]?.count === undefined
							? '- -'
							: item[taskType]?.count}
					</span>
				</div>
			),
			key: taskType,
			dataIndex: taskType,
			render(e, row) {
				return Object.keys(TaskSubMap[taskType]).map(k => (
					<div>
						{TaskSubMap[taskType][k] + ': '}
						<span
							style={e && e[k + '_color'] ? { color: e[k + '_color'] } : {}}
						>
							{e ? e[k] : '- -'}
						</span>
					</div>
				));
			},
		};
	});
};
const bgColor = {
	'#BB0707': 'rgba(187,7,7,.08)',
	'#FF0000': 'rgba(255,0,0,.08)',
	'#F67E23': 'rgba(246,126,35,.08)',
	'#FED831': 'rgba(254,216,49,.08)',
	'#11AB4E': 'rgba(17, 171, 78, .08',
};
const typeLevel = [
	'critical',
	'high',
	'medium',
	'black_links',
	'foreign_links',
	'cryjack',
	'malscan',
	'low',
	'broken_links',
	'keyword',
	'privacy_disclosure',
	'structure',
	'text',
	'resource',
];
const levelColor = {
	5: '#BB0707',
	4: '#FF0000',
	3: '#F67E23',
	2: '#FED831',
	0: '#11AB4E',
};
const typeColor = {
	critical: '#BB0707',
	high: '#FF0000',
	medium: '#F67E23',
	low: '#FED831',
	black_links: '#FF0000',
	foreign_links: '#FF0000',
	broken_links: '#FED831',
	cryjack: '#FF0000',
	malscan: '#FF0000',
	keyword: '#FED831',
	privacy_disclosure: '#FED831',
	structure: '#FED831',
	text: '#FED831',
	resource: '#FED831',
};
const LEVEL = [
	{ value: '未知', label: '未知' },
	{ value: '安全', label: '安全' },
	{ value: '低危', label: '低危' },
	{ value: '中危', label: '中危' },
	{ value: '高危', label: '高危' },
	{ value: '严重', label: '严重' },
].reverse();
const aliveStatus = [
	{ value: 'error', lable: '异常' },
	{ value: 'normal', lable: '正常' },
	{ value: 'unknown', lable: '未知' },
];
const setT = null;
const defaultFilter = {
	page: 1,
	count: 10,
	asset_type: 'host',
};
// TODO:分为主机资产列表和web资产列表(this.props.match.params.type)host, web

function Jobs({
	className,
	history,
	match: {
		params: { assetType },
	},
	location,
}) {
	const resD = JSON.parse(sessionStorage.resD);
	const hostDomain = pathOr(0, ['balance', 'host'], resD);
	const webDomain = pathOr(0, ['balance', 'domain'], resD);
	const isPlanTimeOut =
		moment().unix() > moment(sessionStorage.planTimeOut).unix();
	const prefilter = new URLSearchParams(location.search).get('filter');
	const filterS = prefilter ? JSON.parse(prefilter) || {} : {};
	const defaultFilter_ = {
		...defaultFilter,
		...filterS,
		asset_type: assetType,
	};
	const [filter, setFilter] = React.useState(defaultFilter_);
	const [loading, setLoading] = React.useState(false);
	const [selectedRows, setSelectedRows] = React.useState([]);
	const [userInfo, setUserInfo] = React.useState({});
	const [columns, setColumns] = React.useState([]);
	const [creatWebVisible, setCreatWebVisible] = React.useState(false);
	const [resultWebVisible, setResultWebVisible] = React.useState(false);
	const [resultWeb, setResultWeb] = React.useState(null);
	const [verWebVisible, setVerWebVisible] = React.useState(false);
	const [verWebData, setVerWebData] = React.useState(null);
	const [verResult, setVerResult] = React.useState('');
	const [verResultVisible, setVerResultVisible] = React.useState(false);
	const [webForm] = Form.useForm();
	const defaultWebRecord = {
		note: '',
		target_url: 'http://',
		asset_type: assetType,
		source_ip: '',
	};
	const [webRecord, setWebRecord] = React.useState(defaultWebRecord);
	const [tableData, setTableData] = React.useState({
		data: [],
		total: 0,
	});
	const [taskResult, setTaskResult] = useState([]);
	const updateWebNote = record => {
		const protocol = [record.target_url.split('//')[0] + '//'];
		const url = record.target_url.split('//')[1];
		webForm?.current?.setFieldsValue({ ...record, protocol, url });
		setWebRecord(record);
		setCreatWebVisible(true);
	};
	const validatormap = (rule, value) => {
		if (rule.field === 'note') {
			if (!value || !value.trim()) {
				return Promise.reject('请输入资产名称');
			} else if (
				!(
					value.trim().replace(/[a-zA-Z0-9_\u4E00-\u9FA5]{1,50}/g, '')
						.length === 0
				)
			) {
				return Promise.reject(
					'名称格式错误，只能输入1～50个中文、英文字母、数字、下划线'
				);
			} else {
				return Promise.resolve();
			}
			// eslint-disable-next-line prefer-promise-reject-errors
		} else {
			return Promise.resolve();
		}
	};
	const handleUpdateJobNote = async record => {
		const updateData = {
			note: record?.note,
			jobId: record?.jobId,
			sourceIp : record?.source_ip
		};
		if (assetType === 'web') {
			webForm.current.validateFields().then(async res => {
				if (res) {
					if (webRecord.job_id) {
						updateData.note = webForm.current.getFieldValue('note');
						updateData.sourceIp = webForm.current.getFieldValue('source_ip');
						updateData.jobId = webRecord.job_id;

						const res = await fetchFer(`/api/v2/asset/asset-update`, {
							method: 'POST',
							body: JSON.stringify(updateData),
						}).catch(error => {
							return error;
						});
						if (res.message === '修改成功') {
							if (assetType === 'web') setCreatWebVisible(false);
							Message.show({
								type: 'success',
								message: res.message,
								onclose() {
									getData();
								},
							});
						} else {
							Message.show({ type: 'error', message: res.message || res.msg });
						}
						return res;
					} else {
						const note = webForm.current.getFieldValue('note');
						const target_url =
							webForm.current.getFieldValue('protocol')[0] +
							webForm.current.getFieldValue('url');
						const source_ip = webForm.current.getFieldValue('source_ip');
						handleCreateJob({ note, target_url, source_ip });
					}
				}
			});
		} else {
			const res = await fetchFer(`/api/v2/asset/asset-update`, {
				method: 'POST',
				body: JSON.stringify(updateData),
			}).catch(error => {
				return error;
			});
			if (res.message === '修改成功') {
				if (assetType === 'web') setCreatWebVisible(false);
				Message.show({
					type: 'success',
					message: res.message,
					onclose() {
						getData();
					},
				});
			}
			return res;
		}
	};
	const initColumns = userInfo_ => {
		if (assetType === 'web') {
			const WebColumns_ = cloneDeep(WebColumns);
			if (WebColumns_.length <= WebColumns.length) {
				WebColumns_.push({
					title: '操作',
					dataIndex: 'is_verified',
					width: 100,
					key: 'is_verified',
					render(e, record) {
						return (
							<div className={s.controlContainer}>
								<div className={s.control}>
									{e ? (
										<>
											<Link
												className={s.itemSpan}
												to={{
													pathname: `/asset-manage/manage/web/Detail`,
													search: `jid=${record.job_id}&url=${record.target_url}`,
												}}
											>
												详情
											</Link>
											{resD.plan_name !== '免费版' &&
												resD.plan_name !== '源站安全检测' && (
													<Dropdown
														overlay={
															<Menu>
																<Menu.Item key="1">
																	{isPlanTimeOut ||
																	(!resD?.feature?.vulTask &&
																		!resD?.feature?.vulManualTask &&
																		!resD?.feature?.sslTask &&
																		!resD?.feature?.sslManualTask &&
																		!resD?.feature?.securityEventTask &&
																		!resD?.feature?.securityEventManualTask &&
																		!resD?.feature?.contentTask &&
																		!resD?.feature?.contentManualTask) ? (
																		<span
																			className={s.MenuSpan}
																			onClick={() => {
																				return Message.show({
																					type: 'error',
																					message: '请先升级套餐服务',
																				});
																			}}
																		>
																			下发任务
																		</span>
																	) : (
																		<span
																			className={s.MenuSpan}
																			onClick={() => {
																				window.location.href = `/#/job-manage/create-job-all?assetType=web&jid=${record.job_id}&isSchedule=${record.web_security_schedule_task}`;
																			}}
																		>
																			下发任务
																		</span>
																	)}
																</Menu.Item>
																<Menu.Item key="2">
																	<span
																		className={s.MenuSpan}
																		onClick={() => updateWebNote(record)}
																	>
																		编辑
																	</span>
																</Menu.Item>
																<Menu.Item key="3">
																	<span
																		className={s.MenuSpan}
																		onClick={() => handleDelete(record.job_id)}
																	>
																		删除
																	</span>
																</Menu.Item>
															</Menu>
														}
														trigger={['click']}
														getPopupContainer={triggerNode =>
															triggerNode.parentElement
														}
													>
														<a
															className={s.dropdown}
															onClick={e => e.preventDefault()}
														>
															管理
															<ChevronDown />
														</a>
													</Dropdown>
												)}
										</>
									) : (
										<>
											<span
												className={s.itemSpan}
												onClick={() => {
													if (isPlanTimeOut) {
														return Message.show({
															type: 'error',
															message: '当前套餐已过期，无法进行资产认证。',
														});
													} else {
														verWebJob(record);
													}
												}}
											>
												认证
											</span>
											<Dropdown
												overlay={
													<Menu>
														<Menu.Item key="4">
															<span
																className={s.MenuSpan}
																onClick={() => updateWebNote(record)}
															>
																编辑
															</span>
														</Menu.Item>
														<Menu.Item key="5">
															<span
																className={s.MenuSpan}
																onClick={() => handleDelete(record.job_id)}
															>
																删除
															</span>
														</Menu.Item>
													</Menu>
												}
												trigger={['click']}
												getPopupContainer={triggerNode =>
													triggerNode.parentElement
												}
											>
												<a
													className={s.dropdown}
													onClick={e => e.preventDefault()}
												>
													管理
													<ChevronDown />
												</a>
											</Dropdown>
										</>
									)}
								</div>
							</div>
						);
					},
				});
				setColumns(WebColumns_);
			}
		} else {
			const HostColumns_ = cloneDeep(HostColumns);
			if (HostColumns_.length <= HostColumns.length) {
				HostColumns_.push({
					title: '操作',
					dataIndex: 'is_verified',
					width: 100,
					key: 'is_verified',
					render(e, record) {
						return (
							<div className={s.controlContainer}>
								<div className={s.control}>
									{e ? (
										<>
											<Link
												className={s.itemSpan}
												to={{
													pathname: `/asset-manage/manage/host/Detail`,
													search: `jid=${record.job_id}&url=${record.target_url}`,
												}}
											>
												详情
											</Link>
											<Dropdown
												overlay={
													<Menu>
														<Menu.Item key="1">
															{isPlanTimeOut ||
															(!resD.feature.hostVulTask &&
																!resD.feature.hostVulManualTask) ? (
																<span
																	className={s.MenuSpan}
																	onClick={() => {
																		return Message.show({
																			type: 'error',
																			message: '请先升级套餐服务',
																		});
																	}}
																>
																	下发任务
																</span>
															) : (
																<span
																	className={s.MenuSpan}
																	onClick={() => {
																		window.location.href = `/#/job-manage/create-job-all?assetType=host&jid=${record.job_id}&isSchedule=${record.host_schedule_task}`;
																	}}
																>
																	下发任务
																</span>
															)}
														</Menu.Item>
														<Menu.Item key="2">
															<CreateHostJob
																onSubmit={handleUpdateJobNote}
																record={record}
																isDialog={true}
																userInfo={userInfo_}
															>
																<span className={s.MenuSpan}>编辑</span>
															</CreateHostJob>
														</Menu.Item>
														<Menu.Item key="3">
															<span
																className={s.MenuSpan}
																onClick={e => {
																	handleDelete(record.job_id);
																}}
															>
																删除
															</span>
														</Menu.Item>
													</Menu>
												}
												trigger={['click']}
												getPopupContainer={triggerNode =>
													triggerNode.parentElement
												}
											>
												<a
													className={s.dropdown}
													onClick={e => e.preventDefault()}
												>
													管理
													<ChevronDown />
												</a>
											</Dropdown>
										</>
									) : (
										<>
											<Tooltip
												placement="top"
												overlay={'请联系技术支持人员认证资产。'}
											>
												<span className={s.itemSpan}>认证</span>
											</Tooltip>
											<Dropdown
												// visible={true}
												overlay={
													<Menu>
														<Menu.Item key="2">
															<CreateHostJob
																onSubmit={handleUpdateJobNote}
																record={record}
																isDialog={true}
																userInfo={userInfo_}
															>
																<span className={s.MenuSpan}>编辑</span>
															</CreateHostJob>
														</Menu.Item>
														<Menu.Item key="3">
															<span
																className={s.MenuSpan}
																onClick={e => {
																	handleDelete(record.job_id);
																}}
															>
																删除
															</span>
														</Menu.Item>
													</Menu>
												}
												trigger={['click']}
												getPopupContainer={triggerNode =>
													triggerNode.parentElement
												}
											>
												<a
													className={s.dropdown}
													onClick={e => e.preventDefault()}
												>
													管理
													<ChevronDown />
												</a>
											</Dropdown>
										</>
									)}

									{/* <div className={s.lineBtn}>
										<Button
											link
											className={s.itemSpan}
											onClick={() => {
												handleDelete(record.job_id);
											}}
										>
											删除
										</Button>
									</div> */}
								</div>
							</div>
						);
					},
				});
				setColumns(HostColumns_);
			}
		}
	};
	const verWebJob = record => {
		setVerWebData(record);
		setVerWebVisible(true);
	};
	const handleDelete = id => {
		const jobId = id ? [id] : selectedRows.map(row => row.job_id);
		confirm.warning({
			message: `删除资产对应检测任务将同步删除，操作不可逆，您确定要删除所选资产？`,
			okText: '删除',
			cancelText: '取消',
			title: '',
			onCancel: () => {
				setSelectedRows([]);
			},
			onOk: async () => {
				const res = await fetchFer(`/api/v2/asset/asset-del`, {
					method: 'POST',
					body: JSON.stringify({ jobId }),
				});
				if (res.code === 0) {
					notification.success({
						placement: 'top',
						message: `删除成功`,
					});
					getData();
					getResD();
				} else {
					notification.error({
						message: '删除失败',
						placement: 'top',
					});
				}
				setSelectedRows([]);
			},
		});
	};
	const taskRes = row => {
		return (
			<Tooltip
				overlayClassName={s.taskResTooltip}
				overlay={
					<Table
						className={s.resultTable}
						columns={resultCol(
							Object.keys(row?.last_result).reduce((t, i) => {
								t[i] = {
									count: row?.last_result[i].count,
									color: row?.last_result[i].color,
								};
								return t;
							}, {})
						)}
						data={[row?.last_result]}
					></Table>
				}
				placement={'topRight'}
			>
				<div className={s.resultBox}>
					{Object.keys(TaskMap).map(i => (
						<span
							style={{
								color: row?.last_result[i]?.color || '#686C78',
								backgroundColor:
									bgColor[row?.last_result[i]?.color] || '#E6EAEF',
							}}
						>
							{row?.last_result[i]?.hasOwnProperty('count')
								? row?.last_result[i].count > 99
									? '99+'
									: row?.last_result[i].count
								: '- -'}
						</span>
					))}
				</div>
			</Tooltip>
		);
	};
	const getData = async (e, f) => {
		setLoading(true);
		const senddata = f === 'r' ? e : { ...filter, ...e };
		const params = turnToUrlparam(senddata);
		// TODO: handle
		// const urlType =
		// 	assetType === 'web'
		// 		? '/api/v2/asset/asset-result'
		// 		: '/api/v2/asset/asset_list';
		const urlType = '/api/v2/asset/asset_list';
		const res = await fetchFer(`${urlType}?${params}`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(() => {
			return {};
		});
		if (res.data.results.length < 1 && senddata.page > 1) {
			setFilter({ ...filter, limit: 10, page: senddata.page - 1 });
			getData({ limit: 10, page: senddata.page - 1 });
			return false;
		}
		setTableData({
			data: res.data.results.map(e => {
				return { ...e, key: e, taskRes: taskRes,enable_task:false, last_result: assetType === 'web' ? Object.keys(e.last_result).reduce((t, k) => {
					if (k !== 'score' && k !== 'security_event_severity' && e.last_result[k]?.hasOwnProperty('count')) {
						let level = -1 // 等级越小越高, 默认未知
						e.last_result[k].color = levelColor['0'] // 颜色默认安全
						Object.keys(TaskSubMap[k]).map(t => {
							if (e.last_result[k][t]) {
								if ((level > -1 && typeLevel.indexOf(t) < level) || level === -1) { // 监测项总等级
									level = typeLevel.indexOf(t)
									e.last_result[k].color = typeColor[t]
								}
								if (k === 'security_event' && e.last_result.security_event_severity) {
									e.last_result[k][t + '_color'] = levelColor[e.last_result.security_event_severity[t]] || ''
									e.last_result[k].color = levelColor[Object.values(e.last_result.security_event_severity).sort((a, b) => { return Number(b) - Number(a) })[0]] || ''
								} else {
									e.last_result[k][t + '_color'] = typeColor[t] || ''
								}
							}
						})
					}
					t[k] = e.last_result[k]
					return t
				}, {}) : e.last_result };
			}),
			total: res.data.count,
		});
		setLoading(false);
		// emptyType: 'img',
	};
	const handleCreateJob = async record => {
		let url = null;
		let addData = null;
		if (assetType === 'host') {
			url = '/api/v2/asset/host_asset_add';
			addData = {
				note: record.note,
				target_urls: record.target_urls,
				asset_type: 'host',
			};
		} else {
			url = '/api/v2/asset/asset_add';
			addData = {
				note: record.note,
				target_url: record.target_url,
				asset_type: 'web',
				source_ips: record.source_ip.split('\n'),
			};
		}
		const resp = await fetchFer(url, {
			method: 'POST',
			body: JSON.stringify(addData),
			checkStatus: 501,
		});
		if (resp.code === 0 && assetType === 'host') {
			notification.success({
				placement: 'top',
				message: `添加成功，请联系技术支持人员认证资产。`,
			});
			getData();
		}
		if (assetType === 'web') {
			if (resp.message?.indexOf('失败') > -1) {
				setResultWeb(resp.data);
				setResultWebVisible(true);
			} else {
				if (resp.code === 0) {
					setCreatWebVisible(false);
					if (resp?.data?.detail.length > 0) {
						getResD();
						getData();
						let res = resp?.data?.detail[0]
						res.task={
							asset_task_checked:0
						};
						verWebJob(res);
					} else {
						Message.show({
							type: 'success',
							message: resp.msg || resp.message,
							onclose() {
								getResD();
								getData();
							},
						});
					}
				} else {
					Message.show({
						type: resp.code === 0 ? 'success' : 'error',
						message: resp.msg || resp.message,
						onclose() {
							getResD();
							getData();
						},
					});
				}
			}
		}
		return resp;
	};
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRows(newSelectedRowKeys);
	};
	const handleChangeSearch = e => {
		let filter_ = null;
		if (e?.page) {
			filter_ = { ...filter, ...e };
		} else {
			filter_ =
				e === 'r'
					? { asset_type: assetType }
					: { ...filter, ...e, page: 1, count: 10 };
		}
		const backparams = JSON.stringify(filter_);
		const searchString = 'filter=' + encodeURI(backparams);
		history.replace(`/asset-manage/manage/${assetType}?${searchString}`);
		setFilter(filter_);
		getData(filter_, e);
	};
	const backCreate = () => {
		const targetUrl = resultWeb.detail[0].target_url;
		const protocol = [targetUrl.split('//')[0] + '//'];
		const url = targetUrl.split('//')[1];
		const note = resultWeb.detail[0].note;
		const source_ip = resultWeb.detail
			.reduce((t, item) => {
				t.push(item.source_ip);
				return t;
			}, [])
			.join('\n');
		webForm?.current?.setFieldsValue({ note, source_ip, protocol, url });
		setWebRecord({ target_url: targetUrl, note, source_ip });
		setCreatWebVisible(true);
	};
	const handleEnableTaskChange=e=>{
		setVerWebData(prev=>({
			...prev,
			enable_task:e.target.checked
		}))
	}
	const handleVerCheck = () =>
		// ownershipCheck({ variables: { jobId: job._id } })
		fetchFer(`/api/v2/asset/asset-verify`, {
			method: 'POST',
			body: JSON.stringify({
				jobId: verWebData.job_id,
				enableTask : verWebData.enable_task
			 }),
		})
			.then(resp => {
				const isVerified = resp.code;
				setVerWebVisible(false);
				setVerResultVisible(true);
				setVerResult(isVerified == 0 ? 'success' : 'fail');
			})
			.catch(() => {
				setVerWebVisible(false);
				setVerResultVisible(true);
				setVerResult('fail');
			});
	const cascaderSearchFilter = (inputValue, path) =>
		path.some(
			option =>
				option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
		);
	React.useMemo(async () => {
		const res = await fetchFer(`/api/v2/users/user_info`, {
			method: 'GET',
		});
		setUserInfo(res.results);
		initColumns(res.results);
	}, [assetType]);
	React.useEffect(() => {
		getData({ asset_type: assetType });
	}, [assetType]);
	return (
		<div className={cn(className, s.tasks)}>
			<div className={s.tasksContent}>
				<div className={cn('df aic jcsb')}>
					<Breadcrumb className={s.breadCrumb}>
						<Item key="" disabled>
							资产管理
						</Item>
						<Item key={assetType}>
							{assetType === 'web' ? 'Web资产' : '主机资产'}
						</Item>
					</Breadcrumb>
					<div className="df aic mt2" style={{ marginRight: '24px' }}>
						<div className="tac" style={{ marginRight: '60px' }}>
							<div>
								<span className="fs20 lh20 main-color">
									{assetType === 'web' ? webDomain.used : hostDomain.used}
								</span>
								个
							</div>
							<div>已接入</div>
						</div>
						<div className="tac">
							<div>
								<span className="fs20 lh20 main-color">
									{assetType === 'web'
										? webDomain.total - webDomain.used < 0
											? 0
											: webDomain.total - webDomain.used
										: hostDomain.total - hostDomain.used < 0
										? 0
										: hostDomain.total - hostDomain.used}
								</span>
								个
							</div>
							<div>剩余可接入</div>
						</div>
					</div>
				</div>
				<div className={s.body}>
					<div className={s.controlWapper}>
						<div className={s.firstRow}>
							<div>
								{assetType === 'web' ? (
									<CreateJob
										onSubmit={handleCreateJob}
										isDialog={true}
										maxDomain={webDomain}
										userInfo={userInfo}
										assetType={assetType}
										webData={defaultWebRecord}
										refetch={() => {
											getData();
										}}
									>
										<Button primary={true}>添加资产</Button>
									</CreateJob>
								) : (
									<CreateHostJob
										onSubmit={handleCreateJob}
										isDialog={true}
										maxDomain={hostDomain}
										userInfo={userInfo}
										refetch={() => {
											getData();
										}}
										assetType={assetType}
									>
										<Button primary={true}>添加资产</Button>
									</CreateHostJob>
								)}
								<CreateJob
									isDialog={false}
									userInfo={userInfo}
									maxDomain={assetType === 'web' ? webDomain : hostDomain}
								>
									<Button
										className={s.primary}
										onClick={() =>
											(window.location.href = `/#/asset-manage/manage/batch_add/${assetType}`)
										}
									>
										批量添加
									</Button>
								</CreateJob>
							</div>
						</div>
						<div className={cn(s.selectContainer, 'df aic jcsb mt10')}>
							{/* 资产名称 */}
							<div className="df aic">
								<Input
									className={s.input}
									type="search"
									placeholder="请输入资产名称"
									after={
										<SearchIcon
											className={s.searchIcon}
											onClick={() => {
												handleChangeSearch();
											}}
										/>
									}
									value={filter.note}
									onPressEnter={() => {
										handleChangeSearch();
									}}
									onChange={note => {
										setFilter({ ...filter, note });
									}}
								/>
								{/* 资产地址 */}
								<Input
									className={cn(s.input, 'mr10 ml10')}
									type="search"
									placeholder="请输入资产地址"
									after={
										<SearchIcon
											className={s.searchIcon}
											onClick={() => {
												handleChangeSearch();
											}}
										/>
									}
									value={filter.target_url}
									onPressEnter={() => {
										handleChangeSearch();
									}}
									onChange={target_url => {
										setFilter({ ...filter, target_url });
									}}
								/>
								{/* 源站IP */}
								{assetType === 'web' && (
									<Input
										className={s.input}
										type="search"
										placeholder="请输入源站IP"
										after={
											<SearchIcon
												className={s.searchIcon}
												onClick={() => {
													handleChangeSearch();
												}}
											/>
										}
										value={filter.source_ip}
										onPressEnter={() => {
											handleChangeSearch();
										}}
										onChange={source_ip => {
											setFilter({ ...filter, source_ip });
										}}
									/>
								)}
							</div>
							<div className="df aic">
								{/* 风险等级 */}
								<Select
									placeholder={`${assetType === 'web' ? '风险' : '威胁'}等级`}
									className={s.itemSel}
									value={filter.level}
									allowClear={true}
									getPopupContainer={triggerNode => triggerNode}
									onChange={level => {
										handleChangeSearch({ level });
									}}
								>
									{LEVEL.map(e => (
										<Option key={e.value} value={e.value} selected>
											{e.label}
										</Option>
									))}
								</Select>
								{/* 监测结果 */}
								{/* {assetType === 'web' && ( */}
								<Cascader
									size="middle"
									showSearch={{ filter: cascaderSearchFilter }}
									getPopupContainer={node => node.parentElement}
									popupClassName={'cascaderItem'}
									className={cn('ml10 mul-cascader w160')}
									options={casList}
									suffixIcon={<span className="cascader-icon"></span>}
									value={
										filter?.monitor_type && filter?.task_level + ''
											? [filter?.monitor_type, filter?.task_level]
											: []
									}
									onChange={e => {
										handleChangeSearch({
											monitor_type: e[0],
											task_level: e[1],
										});
									}}
									placeholder="监测结果"
								/>
								{/* )} */}
								{/* 认证状态 */}
								<Select
									placeholder="认证状态"
									className={s.itemSel}
									value={filter.is_verified}
									allowClear={true}
									getPopupContainer={triggerNode => triggerNode}
									onChange={is_verified => {
										handleChangeSearch({ is_verified });
									}}
								>
									<Option key={'已认证'} value={true} selected>
										已认证
									</Option>
									<Option key={'未认证'} value={false} selected>
										未认证
									</Option>
								</Select>
								<Button
									className={s.btn}
									onClick={() => {
										// setFilter(defaultFilter);
										handleChangeSearch('r');
									}}
								>
									重置
								</Button>
							</div>
						</div>
					</div>

					{userInfo.uid && (
						<>
							<Table
								className={s.jobTable}
								key={Math.random().toString(36).slice(-6)}
								rowSelection={{
									selectedRowKeys: selectedRows,
									onChange: onSelectChange,
								}}
								empty={<EmptyData type={'img'} className={s.empty2} />}
								loading={loading}
								pro
								columns={columns}
								data={tableData.data}
							/>
							<div className={s.secondRow}>
								<div className={s.batchBtn}>
									<div className={s.lineBtn}>
										<Button
											link
											disabled={!selectedRows.length}
											className={{ [s.highLight]: selectedRows.length }}
											onClick={() => {
												handleDelete();
											}}
										>
											批量删除
										</Button>
									</div>
								</div>
								{tableData.total > 10 && (
									<Pagination
										current={filter.page || 1}
										pageSize={filter.count || 10}
										total={tableData.total}
										pageSizeOptions={[10, 20, 50]}
										showSizeChanger
										showQuickJumper
										showTotal={total => `共${total}条`}
										onChange={(page, count) => {
											handleChangeSearch({ page, count });
										}}
									/>
								)}
							</div>
						</>
					)}
					<KDialog
						visible={creatWebVisible}
						className={s.w550}
						title={(webRecord.job_id ? '修改' : '添加') + '资产'}
						onhide={() => {
							setCreatWebVisible(false);
							webForm.current.resetFields();
						}}
						onsubmit={handleUpdateJobNote}
					>
						<div className={cn(s.p20_0, s.createForm)}>
							<Form
								ref={webForm}
								labelCol={{ span: 5 }}
								onValuesChange={(newItem, allValues) => {
									const val = recursion(newItem);
									function recursion(obj) {
										const obj_ = obj;
										const key = Object.keys(obj_);
										if (obj_[key] && typeof obj_[key] === 'object') {
											if ({}.propertyIsEnumerable.call(obj_[key], 'value')) {
												obj_[key] = obj_[key].value;
											} else if (
												{}.propertyIsEnumerable.call(obj_[key], 'selectedItem')
											) {
												if (obj_[key].selectedItem.length > 0) {
													if (obj_[key].selectedItem.length > 1) {
														obj_[key] = obj_[key].selectedItem.map(
															item => item.value
														);
													} else {
														obj_[key] = [obj_[key].selectedItem[0].value];
													}
												} else if (obj_[key].selectedItem.length === 0) {
													obj_[key] = [];
												}
											} else {
												obj_[key] = recursion(obj_[key]);
											}
										}
										return obj_;
									}
									webForm.current.setFieldsValue(val);
								}}
								wrapperCol={{ span: 18 }}
								initialValues={{ remember: true }}
							>
								<Form.Item
									label="资产名称"
									name="note"
									rules={[{ required: true, validator: validatormap }]}
								>
									<KInput placeholder="请输入资产名称" />
								</Form.Item>
								<Form.Item
									label="资产地址"
									name="url"
									rules={[{ required: true, message: '资产地址不能为空' }]}
								>
									<div className={cn(s.df, s.aic, s.bdt, 'error-box')}>
										<Form.Item noStyle name="protocol">
											<KSelect
												disabled={!!webRecord.job_id}
												id={s.webDisabledItem}
												className={cn(s.w80, s.appendSelect)}
												option={[
													{ label: 'http://', value: 'http://' },
													{ label: 'https://', value: 'https://' },
												]}
											/>
										</Form.Item>
										<Form.Item noStyle name="url">
											<KInput
												disabled={!!webRecord.job_id}
												id={s.webDisabledItem}
												className={s.flex1}
												placeholder="请输入资产地址"
											/>
										</Form.Item>
										<Tooltip
											overlay={
												<div>
													协议+子域名/IPv4/IPv6+端口
													<br />
													示例：http://www.example.com:80
													<br />
													<span className="_tipSpan_7z5aq_29">
														http://[AD80:0000:0000:0000:ABAA:0000:00C2:0002]
													</span>
													<br />
													<span className="_tipSpan_7z5aq_29">
														https://1.1.1.1
													</span>
													<br />
												</div>
											}
											placement="top"
											children={
												<Icon
													type="question"
													className={cn(s.cp, s.pa, s.r_20, s.fs20)}
												/>
											}
										></Tooltip>
									</div>
								</Form.Item>
								<Form.Item
									label="源站IP"
									name="source_ip"
									validateStatus="warning"
									// help="注：资产认证后，系统默认一周一次监测频率探测资产信息。"
								>
									<KInput
										id={s.webDisabledItem}
										placeholder="请输入源站 IP "
									/>
								</Form.Item>
							</Form>
						</div>
					</KDialog>
					<KDialog
						visible={resultWebVisible}
						className={s.w700}
						title="提示"
						cancelText={<div onClick={backCreate}>返回修改</div>}
						onhide={() => {
							setResultWebVisible(false);
						}}
						onsubmit={() => setResultWebVisible(false)}
					>
						{resultWeb && (
							<div className={s.p20_0}>
								<div className={s.mb20}>
									共计：{resultWeb.summary.total}
									<span className={s.m0_20}>
										成功：{resultWeb.summary.success}
									</span>
									失败：{resultWeb.summary.fail}
								</div>
								<div className={s.mb10}>添加失败的资产如下：</div>
								<Table
									columns={[
										{
											title: '资产名称',
											key: 'note',
											dataIndex: 'note',
											render(e) {
												return (
													<Tooltip overlay={e} placement="top">
														<span>{e}</span>
													</Tooltip>
												);
											},
										},
										{
											title: '资产地址',
											key: 'target_url',
											dataIndex: 'target_url',
											render(e) {
												return (
													<Tooltip overlay={e} placement="top">
														<span>{e}</span>
													</Tooltip>
												);
											},
										},
										{
											title: '源站IP',
											key: 'source_ip',
											dataIndex: 'source_ip',
										},
										{
											title: '失败原因',
											key: 'reason',
											dataIndex: 'reason',
											render(e) {
												return (
													<Tooltip overlay={e} placement="top">
														<span>{e}</span>
													</Tooltip>
												);
											},
										},
									]}
									data={resultWeb.detail}
								/>
							</div>
						)}
					</KDialog>
					<KDialog
						visible={verResultVisible}
						className={s.w500}
						title="认证结果"
						confirmText={verResult === 'fail' ? '重新认证' : '前往下发任务'}
						onhide={() => { setVerResultVisible(false)
							            if(verResult ==='success') getData()}}
						onsubmit={
							verResult === 'fail'
								? handleVerCheck
								: () => {
										window.location.href = `/#/job-manage/create-job-all/?assetType=web&jid=${verWebData.job_id}`;
								  }
						}
					>
						{verWebData && (
							<div className={s.p20_0}>
								<div className={cn(s.tac, s.mb10)}>
									<Icon
										type={verResult === 'fail' ? 'cancel-circle' : 'success'}
										className={cn(
											s.fs36,
											{ [s.errorColor]: verResult === 'fail' },
											{ [s.successColor]: verResult === 'success' }
										)}
									/>
								</div>
								<div className={cn(s.tac, s.mb10)}>
									{`资产${verWebData.note}，` +
										verWebData.target_url +
										(verWebData.source_ip
											? `(${verWebData.source_ip})`
											: '')}{' '}
									认证{verResult === 'fail' ? '失败' : '成功'}！
								</div>
								<div>
									{verResult === 'fail'
										? '请确保认证文件已上传到网站根目录，并能正常访问。如有疑问，请联系在线客服。'
										: '系统将默认按一周一次频率探测资产信息，您也可以前往任务管理下发Web安全监测任务。'}
								</div>
							</div>
						)}
					</KDialog>
					<KDialog
						visible={verWebVisible}
						className={s.w600}
						title={
							<span className={s.titleContainer}>
								网站认证权限
								<KTooltip
									placement="top"
									overlayClassName={s.helpTooltip}
									overlay={
										<div>
											因国家安全法规要求，禁止添加第三方网站（不属于自身所有权范围）资产，
											<br />
											为保证操作合法性，须通过文件认证方式，证明资产属于您的合法资产。
										</div>
									}
								>
									<Icon type="question" className={cn(s.ml5, s.vam, s.cp)} />
								</KTooltip>
							</span>
						}
						confirmText="开始认证"
						onhide={() => {
							setVerResult('');
							setVerWebVisible(false);
						}}
						onsubmit={handleVerCheck}
					>
						{verWebData && (
							<div className={s.p20_0}>
								<Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
									<Form.Item label="认证站点" name="target_url">
										<div>
											{`资产${verWebData.note}，` +
												verWebData.target_url +
												(verWebData.source_ip
													? `(${verWebData.source_ip})`
													: '')}
										</div>
									</Form.Item>
									<Form.Item label="认证步骤">
										<div>
											1、点击
											<a
												href={`/api/v1/challenge-file/${verWebData.job_id}`}
												target="_blank"
												rel="noopener noreferrer"
											>
												下载认证文件
											</a>
											，将认证文件下载到本地；
										</div>
										<div>
											2、将下载的认证文件上传到网站根目录，请勿修改文件名称和内容；
										</div>
										<div>
											3、确保能从公网访问该文件，
											<a
												href={`${verWebData.target_url}/${verWebData.challenge}.txt`}
												target="_blank"
												rel="noopener noreferrer"
											>
												点击访问
											</a>
											；
										</div>
										<div>4、点击下方“开始认证”按钮开始验证。</div>
										{verWebData.task.asset_task_checked >= 1 && (
											<div className='mt20'>
												  <Checkbox  checked={verWebData.enable_task} onChange={handleEnableTaskChange} />
												  <span className='ml5'>开启已经存在的周期监测任务</span>
										  </div>
										)}
									</Form.Item>
								</Form>
							</div>
						)}
					</KDialog>
				</div>
			</div>
		</div>
	);
}
Jobs.propTypes = {
	className: PropTypes.string,
	history: PropTypes.shape({
		push: PropTypes.func,
		replace: PropTypes.func,
	}),
	location: PropTypes.shape({
		search: PropTypes.string,
	}),
	match: PropTypes.any,
	data: PropTypes.shape({
		refetch: PropTypes.func.isRequired,
		JobMany: PropTypes.arrayOf(
			PropTypes.shape({
				_id: PropTypes.string.isRequired,
				host: PropTypes.string.isRequired,
				domain: PropTypes.string.isRequired,
			})
		),
		BalanceOne: PropTypes.shape({
			uid: PropTypes.string.isRequired,
			balance: PropTypes.shape({
				domain: PropTypes.shape({
					value: PropTypes.number.isRequired,
				}),
			}),
		}),
		UserOne: PropTypes.shape({
			_id: PropTypes.string.isRequired,
			identified: PropTypes.bool.isRequired,
		}),
	}),
	jobUpdateOne: PropTypes.func,
	jobRemove: PropTypes.func,
	jobCreateOne: PropTypes.func,
};
export default withRouter(Jobs);
